from c_code import obj_c_tools
import copy
import config
import os

doc1 = config.read_json(f"{config.path}/locale/config.json")["doc"]
dict_data = {"doc": doc1}
dict_data["Личные"] = []
dict_data["Оборудование"] = []
dict_data["Система"] = []
dict_data["Прочее"] = []


def enter_icon(dict_icon):
    dict_icon = {int(k): v for k, v in dict_icon.items()}
    if dict_icon:
        list_key_icon = list(dict_icon.keys())
        list_key_icon.sort(reverse=True)
        return dict_icon[list_key_icon[0]]
    else:
        return ""


def merge_twoDict(a, b):
    return dict(a, **b)


def searhc_icon(name):
    dict_icon = {}
    name = name + ".png"
    path = "/usr/share/icons/HighContrast"
    for dir1 in os.listdir(path):
        if os.path.isdir(f"{path}/{dir1}"):
            list_png = os.listdir(f"{path}/{dir1}/apps")
            if name in list_png:
                index = dir1.find("x")
                if index != -1:
                    path_icon = f"{path}/{dir1}/apps/{name}"
                    dict_icon[int(dir1[0:index])] = path_icon
    return dict_icon


def pars_file():
    len_struct = obj_c_tools.len_struct()
    for i in range(0, len_struct):
        dict_exec = {}
        struct_data = obj_c_tools.get_data(i)
        str_UBL = struct_data.X_UBLHelpPage.decode().replace("\n", "")
        icon = struct_data.Icon.decode().replace("\n", "")
        struct_data.Icon.decode().replace("\n", "")
        name = ""
        categories = struct_data.Categories.decode().replace("\n", "")
        exec_str = struct_data.Exec.decode().replace("\n", "")
        categories_flag = []

        if config.lang_os == "ru_RU":
            name = struct_data.Name_ru.decode().replace("\n", "")
        else:
            name = struct_data.Name.decode().replace("\n", "")
        icon = enter_icon(searhc_icon(icon))
        dict_info = {"text": name, "link": str_UBL, "icon": icon, "call_app": exec_str}
        if categories.find("X-UBL-SettingsManager;X-UBL-PersonalSettings") != -1:
            categories_flag.append("Личные")
            dict_data["Личные"].append(dict_info)
        elif categories.find("X-UBL-SettingsManager;X-UBL-HardwareSettings") != -1:
            categories_flag.append("Оборудование")
            dict_data["Оборудование"].append(dict_info)
        elif categories.find("X-UBL-SettingsManager;X-UBL-SystemSettings") != -1:
            categories_flag.append("Система")
            dict_data["Система"].append(dict_info)
        elif categories.find("X-UBL-SettingsManager") != -1:
            categories_flag.append("Прочее")
            dict_data["Прочее"].append(dict_info)
    config.write_json(f"{config.path}/locale/config.json", dict_data)


pars_file()